package com.rules.admin.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestAndResponseContextHolder {
    public static final String RESPONSE_NAME_AT_ATTRIBUTES = ServletRequestAttributes.class.getName() + ".ATTRIBUTE_NAME";

    public RequestAndResponseContextHolder() {
    }

    public static final HttpServletResponse response() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = null;
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
            response = (HttpServletResponse)servletRequestAttributes.getAttribute(RESPONSE_NAME_AT_ATTRIBUTES, 0);
        }

        return response;
    }

    public static final HttpServletRequest request() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
            request = servletRequestAttributes.getRequest();
        }

        return request;
    }

    public static final SavedRequest savedRequest() {
        return (SavedRequest)request().getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    }

    public static void setResponse(HttpServletResponse response) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
            servletRequestAttributes.setAttribute(RESPONSE_NAME_AT_ATTRIBUTES, response, 0);
        }

    }
}
